package cn.e2win.biz.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.e2win.biz.dbo.*;
import org.hsqldb.lib.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.e2win.base.entity.SysRole;
import cn.e2win.base.entity.SysUser;
import cn.e2win.base.entity.SysUserRole;
import cn.e2win.base.json.vo.Pager;
import cn.e2win.base.json.vo.Result;
import cn.e2win.biz.annotation.PageParam;
import cn.e2win.biz.base.BaseController;
import cn.e2win.biz.base.BaseService;
import cn.e2win.biz.comm.ViewExcel;
import cn.e2win.biz.util.StringUtils;


@Controller
@Scope("request")
@RequestMapping("/sys/user")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	@Override
	public BaseService initService() {
		return userService;
	}

	@RequestMapping("toEdit/{id}")
	public String toEdit(HttpServletRequest request, @PathVariable(ID) Integer id, ModelMap modelMap){
		SysUser obj = (SysUser)userService.getEntity(SysUser.class, id);
		modelMap.put(OBJECT, obj);
		return "user/userEdit";
	}

	@RequestMapping("edit")
	@ResponseBody
	public Result edit(HttpServletRequest request,@ModelAttribute SysUser obj,ModelMap modelMap){
		Result r = new Result();
		try{
			BaseEmp currEmp = null;
			if("CyzjEmp".equals(obj.getUserType())){
				currEmp = new CyzjEmp();
			}else if("CygsEmp".equals(obj.getUserType())){
				currEmp = new CygsEmp();
			}else if("DsEmp".equals(obj.getUserType())){
				currEmp = new DsEmp();
			}else if("ZdzxEmp".equals(obj.getUserType())){
				currEmp = new ZdzxEmp();
			}
			currEmp.setEmpName(obj.getUserName());
			currEmp.setMobile(obj.getTelNo());
			BaseEmp emp = (BaseEmp) userService.edit(currEmp);
			obj.setEmpId(emp.getId());
			userService.editUser(obj);

		} catch (Exception e) {
			r.setException(e);
		}
		r.setCallbackType(Result.CLOSE_CURRENT);
		r.setNavTabId("listView_"+modelMap.get(FUNID));
		return r;
	}


	@RequestMapping("toDel/{id}")
	public String toDel(HttpServletRequest request, @PathVariable(ID) Integer id, ModelMap modelMap){
		SysUser obj = (SysUser)userService.getEntity(SysUser.class, id);
		modelMap.put(OBJECT, obj);
		return "user/userDel";
	}

	@RequestMapping("del")
	@ResponseBody
	public Result del(HttpServletRequest request,@ModelAttribute SysUser obj,ModelMap modelMap){
		Result r = new Result();
		try{
			String tsf2ProcessorId = request.getParameter("tsf2ProcessorId");
			userService.delUser(obj,tsf2ProcessorId);
			r.setCallbackType(Result.CLOSE_CURRENT);
			r.setNavTabId("listView_"+modelMap.get(FUNID));
		} catch (Exception e) {
			e.printStackTrace();
			r.setException(e);
			logger.error(e);
		}
	    return r;
	}

	@RequestMapping("userPager")
	public String userPager(HttpServletRequest request, ModelMap modelMap){
		Map<String, Object> userSession = (Map<String, Object>)request.getSession().getAttribute("USER");
		pager.getScMap().put("coId", userSession.get("coId")==null?null:userSession.get("coId").toString());
		userService.pagerUser(pager);
		modelMap.put("pager", pager);
		return "user/userPager";
	}

	@RequestMapping("userPagerExcel")
	public ModelAndView customerPagerExcel(HttpServletRequest request, ModelMap modelMap) {
		pager.setReturnAll(true);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("key",userPager(request,modelMap));
		model.put("list", pager.getResultList());
		return new ModelAndView(new ViewExcel(), model);
	}
	
	@RequestMapping("jsonList")
	@ResponseBody
	public Map<String, Object> getJsonList(HttpServletRequest request){
		Map<String, Object> rMap = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for(int i=0;i<10;i++){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id",i);
			map.put("type", i+2000);
			map.put("name", "张三" + i);
			map.put("content", "130000" + i);
			list.add(map);
		}
		rMap.put("result", list);
		rMap.put("totalCounts",200);
		return rMap;
	}
	
	@RequestMapping("toAssign/{id}")
	public String toAssign(HttpServletRequest request, @PathVariable(ID) Integer id, ModelMap modelMap){
		try {
			SysUser obj = (SysUser)userService.getEntity(SysUser.class, id);
			List<SysUserRole> userRoles = userService.getUserRoleListByUserId(id);
			
			List<SysRole> allRoles = roleService.getAllRole();
			for (SysRole oneOfAll : allRoles) {
				for (SysUserRole oneOfUserRole : userRoles) {
					if (oneOfAll.getId().equals(oneOfUserRole.getRoleId())) {
						//暂时用这个字段代替,不会被保存到数据库,只提供给页面来选中
						oneOfAll.setEnable(1);
					}
				}
			}
			
			modelMap.put("allRoles", allRoles);
			modelMap.put(OBJECT, obj);
			return "user/userAssign";
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			return "msg/common/fail";
		}
	}
	
	@RequestMapping("assign")
	@ResponseBody
	public Result assign(HttpServletRequest request,@RequestParam(ID) Integer id,@RequestParam(IDS) Integer[] ids,ModelMap modelMap){
		Result r = new Result();
		r.setCallbackType(Result.CLOSE_CURRENT);
		r.setNavTabId("listView_"+modelMap.get(FUNID));
		userService.assignRoles(id, ids);		
		return r;
	}
	

	
	
	@RequestMapping("toChangePassword")
	public String toChangePassword(HttpServletRequest request, ModelMap modelMap){
	
		return "user/userChangePassword";
	}
	
	@RequestMapping("toPersonalSetting")
	public String toPersonalSetting(HttpServletRequest request, ModelMap modelMap){
	
		return "user/personalSetting";
	}

	@RequestMapping("personalSetting")
	@ResponseBody
	public Result personalSetting(HttpServletRequest request,@ModelAttribute SysUser obj,ModelMap modelMap){
		Result r = new Result();		
		try{
			userService.edit(obj);
		} catch (Exception e) {
			r.setException(e);
		}
		r.setCallbackType(Result.CLOSE_CURRENT);
		r.setNavTabId("listView_"+modelMap.get(FUNID));
		return r;
			
	}
	

	
	@RequestMapping("getUserList")
	@ResponseBody
	public List<Map<String, Object>> getUserList(HttpServletRequest request,
			@PageParam Pager pager, ModelMap modelMap) {
		List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
		try {
			String custName_L = request.getParameter("userName");
			Map<String,Object> paramMap = new HashMap<String, Object>();
			if(!StringUtils.isEmpty(custName_L)){
				paramMap.put("name_L", custName_L);
			}
			r = userService.getUserList(paramMap);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return r;
	}
	
	
	
	
	
	
	
	
	//产品库存列表
	@RequestMapping("logsPager")
	public String logsPager(HttpServletRequest request, 
			ModelMap modelMap) {
		try {
			String jspPath = "user/logsPager";
			userService.pagerLogs(pager);
			modelMap.put("pager", pager);
			return jspPath;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			return "msg/common/fail";
		}
	}
	@RequestMapping("logsPagerExcel")
	public ModelAndView logsPagerExcel(HttpServletRequest request,
			ModelMap modelMap) {
			pager.setReturnAll(true);
			
			Map model = new HashMap();
			model.put("key", logsPager(request,modelMap));	        
			modelMap.put("list", pager.getResultList());  
			
	        return new ModelAndView(new ViewExcel(), model);
		
	}

	@RequestMapping("resetPwd")
	@ResponseBody
	public Result resetPwd(@RequestParam(value = "userType",required = false)String userType,
						   @RequestParam(value = "id",required = false)Integer id){
		Result result = new Result();
		result.setCallbackType("");
		try {
			SysUser sysUser = userService.getUserByType(userType,id);
			sysUser.setPassword("123456");
			userService.edit(sysUser);
		} catch (Exception e) {
			result.setStatusCode(Result.FAILED);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}

		return result;
	}
}
